﻿#region References

using System.Windows;
using System.Windows.Controls;

#endregion

namespace Mss.UiCommon.Helpers
{
    /// <summary>
    /// Two way binding extension.
    /// </summary>
    public static class PasswordBoxExtension
    {
        #region Attached dependency property

        /// <summary>
        /// Using a DependencyProperty as the backing store for BindablePassword.  
        /// This enables animation, styling, binding, etc...
        /// </summary>
        public static readonly DependencyProperty BindablePasswordProperty =
            DependencyProperty.RegisterAttached("BindablePassword", typeof (string), typeof (PasswordBoxExtension),
                                                new UIPropertyMetadata(string.Empty, onBindablePasswordPropertyChanged));

        #endregion

        #region Methods

        /// <summary>
        /// Get stored password value.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetBindablePassword(DependencyObject obj)
        {
            return (string) obj.GetValue(BindablePasswordProperty);
        }

        /// <summary>
        /// Set new password value.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="value"></param>
        public static void SetBindablePassword(DependencyObject obj, string value)
        {
            obj.SetValue(BindablePasswordProperty, value);
        }

        #endregion

        #region Helper Methods

        private static void onBindablePasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var passwordBox = (PasswordBox) d;
            var newPassword = (string) e.NewValue;

            passwordBox.PasswordChanged -= onPasswordChanged;
            passwordBox.PasswordChanged += onPasswordChanged;

            if (!Equals(passwordBox.Password, newPassword))
            {
                passwordBox.Password = newPassword;
            }
        }

        private static void onPasswordChanged(object sender, RoutedEventArgs e)
        {
            var passwordBox = (PasswordBox) sender;
            passwordBox.SetValue(BindablePasswordProperty, passwordBox.Password);
        }

        #endregion
    }
}